import { Component, OnInit, AfterViewInit, Host, ViewChild, ElementRef } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { HttpEvent} from '@angular/common/http';
import { AppComponent } from '../../app.component';
import { AuthenticationService } from './login.service';
import { StorageService } from '../../shared/services/storage.service';
import { TokenModel } from './models/token.model';

/**
 * Login main component
 *
 * Author: Sorin Spiru, Andrei Istrate
 * Date: 13.01.2018
 */
@Component({
    moduleId: module.id,
    templateUrl: 'login.component.html',
    providers: [StorageService],
    styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit, AfterViewInit {
    @ViewChild('passwordField') passwordField: ElementRef;

    public model: any = {};
    public error = false;
    public resetPass = false;
    public showPass = false;
    public agreementType: string;
    public ipLoginUsername: string;

    constructor(
        private router: Router,
        private authenticationService: AuthenticationService,
        @Host() private rootComponent: AppComponent,
        private route: ActivatedRoute
    ) { }

    ngOnInit() {
        // reset login status
        this.authenticationService.logout();

        if (this.router.url == '/login/ip') {
            this.authenticationService.ipLogin().subscribe(
                (result: any) => {
                    this.ipLoginUsername = result.headers.get('username');
                    this.parseLoginResult(result.body, true);
                },
                err => {
                    this.error = true;
                }
            );
        }
    }

    ngAfterViewInit() {
        this.rootComponent.finishLoading();
    }

    login() {
        this.authenticationService.login(this.model.username, this.model.password).subscribe(
            result => this.parseLoginResult(result),
            err => this.error = true
        );
    }

    private parseLoginResult(result: HttpEvent<TokenModel>, ipLogin: boolean = false) {
        if (result && result['access_token']) { // login successful               
            if (ipLogin) this.authenticationService.saveToken(result);
            this.finalizeLogin();
        } else //login failed
            this.error = true;            
    }

    logout() {
        this.authenticationService.logout();
    }

    public toggleShowPassword(): void {
        this.showPass = !this.showPass;
        this.passwordField.nativeElement.type = this.showPass ? 'text' : 'password';
    }

    private finalizeLogin(): void {
        // set auth object
        this.authenticationService.permissions().subscribe(data => {
            //if iplogin, remove the portfolio alert subscriptions
            if (this.router.url == '/login/ip')
                data = data.filter(x => x.resource !== 'api/v1/subscribetoportfolio');

            // set permissions
            StorageService.get().resourcePermissions = data;
            this.authenticationService.profile().subscribe(userInfo => {
                // set user info
                StorageService.get().userInfo = userInfo;                
                this.router.navigate(['/admin', 'home']);
            });
        });
    }
}
